<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" width="120%" destroy-on-close @closed="$emit('closed')" align-center fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="90px" label-position="right">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="承制人">
                        <el-input v-model="info.referred_as"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="发织合同号">
                        <el-input v-model="form.contract_no" v-if="contractShow" disabled></el-input>
                        <el-select v-model="form.contract_no" clearable style="width: 100%" placeholder="请选择" v-else @change="conChange" :disabled="!show" filterable>
                            <el-option v-for="item in contractList" :key="item.contract_no" :label="item.contract_title" :value="item.contract_no" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工厂货号">
                        <el-input v-model="info.factory_number"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="批次号">
                       <el-input v-model="info.batch_number"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工序" prop="two_process_id">
                        <el-select v-model="form.two_process_id" clearable style="width: 100%" placeholder="请选择" @change="processChange" multiple>
                            <el-option v-for="item in twoProcess" :key="item.id" :label="item.title" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="收货日期" prop="take_deliver_date">
                        <el-date-picker v-model="form.take_deliver_date" :value-format="'YYYY-MM-DD'" type="data" placeholder="请选择收货日期" style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-col>
                <div style="margin-left:10px">
                    <el-button v-if="show" type="primary" @click="startSend" :disabled="form.contract_no==''">开始收货</el-button>
                    <el-button v-else type="primary" @click="stopSend">停止收货</el-button>
                </div>
            </el-row>
            <el-container>
                <el-aside width="25.5%">
                    <div style="margin: 15px;height:75%">
                        <div style="text-align: center;margin: 10px;">发织资料</div>
                        <scTable ref="tables" :data="data" @select-all="selectAll" @selection-change="selectionChange" border hideDo hidePagination height="400">
                            <el-table-column type="selection" width="40"></el-table-column>
                            <el-table-column label="颜色" prop="color" align="center"></el-table-column>
                            <el-table-column label="批次号" prop="batch_number" align="center"></el-table-column>
                            <el-table-column label="尺码" prop="goods_size" align="center"></el-table-column>
                            <el-table-column label="可收数" prop="can_take_num" align="center"></el-table-column>
                            <el-table-column label="KG/打" prop="dozen_weight" align="center"></el-table-column>
                        </scTable>
                    </div>
                    <el-footer>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="重量" prop="weight">
                                    <!-- <el-input v-model="info.weight" ref="weightInput" readonly></el-input> -->
                                    <el-input v-model="info.weight" ref="weightInput"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="预计数量" prop="expected_number" >
                                    <el-input v-model="info.expected_number" readonly></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="1">
                            <el-col :span="12">
                                <el-form-item label="实际数量" prop="weight_num" >
                                    <el-input v-model="info.weight_num" readonly></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-button type="primary" style="margin-left:25px" :disabled="selection.length == 0" @click="confirm">确认</el-button>
                            </el-col>
                        </el-row>
                    </el-footer>
                </el-aside>
                <el-main style="height:640px">
                    <sc-form-table ref="table" v-model="form.size_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd showSummary>
                        <el-table-column label="工厂货号" prop="factory_number" align="center"></el-table-column>
                        <el-table-column label="批次号" prop="batch_number" align="center"></el-table-column>
                        <el-table-column label="工序" prop="process_title" align="center"></el-table-column>
                        <el-table-column label="颜色" prop="colour" align="center"></el-table-column>
                        <el-table-column label="尺码" prop="goods_size" align="center"></el-table-column>
                        <el-table-column label="数量" prop="num" align="center"></el-table-column>
                        <el-table-column label="重量" prop="weight" align="center"></el-table-column>
                        <el-table-column label="超数(+)" prop="overnumber" align="center"></el-table-column>
                        <el-table-column label="超重(+)" prop="overweight" align="center"></el-table-column>
                        <el-table-column label="备注" prop="remark" align="center"></el-table-column>
                    </sc-form-table>
                </el-main>
            </el-container>
        </el-form>
	</el-dialog>
    <!-- 收货停止 -->
    <el-dialog v-model="dialog.send" title="此次收货停止,是否提交?" width="500" :before-close="handleClose" align-center>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.send = false">取消</el-button>
                <el-button type="primary" @click="submit(1)">确定</el-button>
                <el-button type="primary" @click="submit(2)">确定并打印收货单</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 超重/轻 -->
    <el-dialog v-model="dialog.weight" :title="checkTitle" width="500" :before-close="handleClose" align-center>
        <el-form-item label="请输入正确的件数" prop="edit_number">
            <el-input v-model="info.edit_number"></el-input>
        </el-form-item>
        <template #footer>
            <!-- <div class="dialog-footer" v-if="!dialog.check">
                <el-button @click="dialog.check = true">否</el-button>
                <el-button type="primary" @click="numSub">是</el-button>
                <el-button type="info" @click="dialog.weight = false">取消</el-button>
            </div> -->
            <div class="dialog-footer">
                <el-button @click="dialog.check = false , dialog.weight = false">取消</el-button>
                <el-button type="primary" @click="sure">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 件数修正 -->
    <!-- <el-dialog v-model="dialog.check" :title="checkTitle" width="500" :before-close="handleClose" align-center>
        <el-form-item label="请输入正确的件数" prop="edit_number" >
            <el-input v-model="info.edit_number"></el-input>
        </el-form-item>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialog.check = false">取消</el-button>
                <el-button type="primary" @click="sure">确定</el-button>
            </div>
        </template>
    </el-dialog> -->
</template>

<script>
    export default {
        emits: ['success', 'closed'],
        data() {
            return {
                mode: "add",
                titleMap: {
                    add: '缝挑电子秤收货',
                    edit: '编辑仓库',
                    show: '查看'
                },
                visible: false,
                isSaveing: false,
                dialog:{
                    send:false,
                    weight:false,
                },
                //表单数据
                form: {
                    remark:"",
                    take_deliver_date: new Date().toISOString().slice(0, 10),
                    delivery_method:1,
                    size_data:[],
	                two_process_id:'',
	                contract_no:'',
				    process_id: 4,
                },
                rules: {
					two_process_id: [
						{required: true, message: '请选择工序'}
					],
				},
                info:{
                    qrcode:"",
                    referred_as: "",
                    factory_number: "",
                    batch_number: "",
                    produce_process_name: "",
                    weight:"",
                    expected_number:"",
                    weight_num:12,
                    edit_number:12,
                },
                weight:"",
                addTemplate: {},
                show:true,
                apply:[],
                data:[],
                twoProcess:[],
                selection:[],
                ports: [],
                port:{},
                connected:null,
                reader:null,
                message:null,
                serialOptions:{
                    baudRate: 9600,
                    flowControl: 'none',
                    dataBits: 8
                },
                checkTitle:"",
                contractShow:false,
                contractList:[],
            }
        },
        mounted () {
            if ("serial" in navigator) {
                this.chooseSerial()
            } else {
                console.log(false);
            }
        },
        created() {
            // this.autoConnectSerial();
        },
        unmounted() {
            this.cutPort()
        },
        methods: {
	        // 手动连接
            async chooseSerial(){
                try {
                    this.port = await navigator.serial.requestPort();
                    this.ports = await navigator.serial.getPorts();
                    console.log('this.port :>> ', this.port);
                    this.openSear()
                } catch (error) {
                    this.$alert(error, "提示", { type: 'error' })
                    return;
                }
            },
            // async autoConnectSerial() {
            //     try {
            //         const ports = await navigator.serial.getPorts();
            //         if (ports.length > 0) {
            //             // 如果有可用端口，直接选择第一个端口进行连接
            //             this.port = ports[0];
            //             await this.openSear();
            //         } else {
            //             this.$alert("未找到可用串口", "提示", { type: 'error' });
            //         }
            //     } catch (error) {
            //         this.$alert(error, "提示", { type: 'error' });
            //     }
            // },
            async openSear(){
                try {
                    await this.port.open(this.serialOptions)
                    this.reader = this.port.readable.getReader()
                    this.connected = true
                    this.readLoop()
                } catch (error) {
                    this.$alert(error, "提示", { type: 'error' })
                    return;
                }
            },
			/**获取数据*/
            async readLoop() {
                try {
                    while (this.connected) {
                        const { value, done } = await this.reader.read()
                        if (done) {
                            this.reader.releaseLock()
                            break
                        }
                        this.message = new TextDecoder().decode(value)
	                    console.log('info.weight',this.message)
                        if(this.message.length==18){
							console.log('info.weight18',this.message)
                            let unit = this.message.substr(14,2).toString()
                            let weight = this.message.substr(7,7).trim()
                            if(unit!='kg'){
                                this.info.weight = weight / 1000
                            }else{
                                this.info.weight = weight
                            }
                            // let base = this.message.substr(0,2)
                            // if(base=='ST'){
                            //     console.log('这里是稳定的输出');
                            //     let type = this.message.substr(3,2)
                            //     if(type=='TR'){
                            //         let unit = this.message.substr(14,2).toString()
                            //         let weight = this.message.substr(7,7).trim()
                            //         if(unit!='kg'){
                            //             this.info.weight = weight / 1000
                            //         }else{
                            //             this.info.weight = weight
                            //         }
                            //         console.log('这里是去皮的输出',this.info.weight);
                            //     }
                            // }
                        }
                    }
                } catch (error) {
                    this.$alert(error, "提示", { type: 'error' })
                }
            },
            // 断开串口
            async cutPort(){
	            if (this.port && this.connected) {
		            await this.reader.cancel();
		            await this.port.close();
		            this.port = "";
	            } else {
		            // this.$alert("错误", "提示", { type: 'error' })
	            }
            },
            //显示
            open(mode = 'add') {
                this.mode = mode;
                this.visible = true;
                return this
            },
            //表单提交方法
            submit(e) {
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res = [];
                        res = await this.$API.produce.contract.loomScanTakeDelivery.post(this.form);
                        if (res.code == 1) {
	                        this.cutPort()
                            this.visible = false;
                            if(e==1){
                                this.$emit('success', this.form, this.mode)
                                this.$message.success("操作成功")
                            }else{
                                var reqData = { deliver_no: res.data.deliver_no, contract_no:res.data.contract_no};
                                var print = await this.$API.print.sendPrint.get(reqData);
                                if (print.code == 1) {
                                    this.$emit('success', this.form, this.mode,print.data)
                                } else {
                                    this.$alert(print.message, "提示", { type: "error" });
                                    this.isSaveing = false;
                                }
                            }
                        } else {
                            this.$alert(res.message, "提示", { type: 'error' })
                            this.isSaveing = false;
                        }
                    } else {
                        return false;
                    }
                })
            },
            //表单注入数据
            async setData(data) {
                let array = []
                if(!data){
                    this.contractShow = false
                    var res = await this.$API.produce.proAll.get({process_id:4,is_completed:0});
                    // this.contractList = res.data
                    res.data.map(item=>{
                        this.contractList.push({
                            contract_no:item.contract_no,
                            contract_title : item.contract_no + ' - ' + item.referred_as + ' - ' + item.factory_number + ' - ' + item.batch_number
                        })
                    })
                }else{
                    this.contractShow = true
                    data.orderDetail.map(item=>{
                        array.push({
                            color:item.colour,
                            batch_number:data.batch_number,
                            goods_size:item.goods_size,
                            can_take_num:item.can_take_num,
                            dozen_weight:item.dozen_weight,
                            weight:item.weight,
                        })
                    })
                    this.data = array
                    this.info.referred_as = data.apply_name
                    this.form.contract_no = data.contract_no
                    this.info.factory_number = data.factory_number
                    this.info.batch_number = data.batch_number
	                this.twoProcess = data.sub_process;
                    let proArray = []
                    let proName = []
                    if(data.sub_process!=''){
                        data.sub_process.map(item=>{
                            proArray.push(
                                item.id
                            )
                            proName.push(
                                item.title
                            )
                        })
                        this.form.two_process_id = proArray
                        this.info.produce_process_name = proName.join("-")
                    }
                }
            },
			/**选合同事件*/
            async conChange(){
                var res = await this.$API.produce.proDetail.get({contract_no:this.form.contract_no});
                let array = []
	            this.twoProcess = res.data.sub_process;
                let proArray = []
                let proName = []
                if(res.data.sub_process!=''){
                    res.data.sub_process.map(item=>{
                        proArray.push(
                            item.id
                        )
                        proName.push(
                            item.title
                        )
                    })
                    this.form.two_process_id = proArray
                    this.info.produce_process_name = proName.join("-")
                }else{
                    this.form.two_process_id = ''
                    this.info.produce_process_name = ''
                }
	            this.info.referred_as = res.data.apply_name
	            this.info.factory_number = res.data.factory_number
	            this.info.batch_number = res.data.batch_number
                res.data.orderDetail.map(item=>{
                    array.push({
                        color:item.colour,
                        batch_number:this.info.batch_number,
                        goods_size:item.goods_size,
                        can_take_num:item.can_take_num,
                        dozen_weight:item.dozen_weight,
                        weight:item.weight,
                    })
                })
                this.data = array
                
            },
            // 开始收货
            startSend(){
                this.show = false
                this.$nextTick(()=>{
                    this.$refs.weightInput.focus()
                })
            },
            // 结束收货
            stopSend(){
                this.dialog.send = true
                this.cutPort()
            },
            // 单选弹框确定
            numSub(){
                this.data.map(item=>{
                    if(item.goods_size == this.selection[0].goods_size){
                        if(this.dialog.check){
                            item.can_take_num = item.can_take_num - this.info.edit_number
                        }
                    }
                })
                this.dialog.weight = false
                let tabData = {
                    contract_no : this.form.contract_no,
                    batch_number : this.selection[0].batch_number,
                    colour : this.selection[0].color,
                    factory_number : this.info.factory_number,
                    process_title : this.info.produce_process_name,
                    goods_size : this.selection[0].goods_size,
                    num : this.info.edit_number,
                    remark : "",
                    weight : this.info.weight,
                    total_weight : this.info.weight,
                    goods_id : this.selection[0].goods_id,
                    overnumber : this.info.expected_number - this.info.weight_num,
                    overweight : (this.info.weight - Number(this.info.weight_num * this.selection[0].weight/1000)).toFixed(2)
                }
                this.form.size_data.push(tabData)
                setTimeout(()=>{
                    this.info.edit_number = 12
                },500)
            },
            sure(){
                if(this.info.edit_number > this.selection[0].can_take_num){
                    this.$alert("超过最大可收数,无法继续收货", "提示", { type: 'error' })
                    return
                }
                var MusicYes = new Audio('https://zhiqiu.mzth.cn/static/img/yes.mp3');
                MusicYes.play()
                this.data.map(item=>{
                    if(item.goods_size == this.selection[0].goods_size){
                        item.can_take_num = item.can_take_num - this.info.edit_number
                    }
                })
                this.dialog.weight = false
                this.dialog.check = false
                let tabData = {
                    contract_no : this.form.contract_no,
                    batch_number : this.selection[0].batch_number,
                    colour : this.selection[0].color,
                    factory_number : this.info.factory_number,
                    process_title : this.info.produce_process_name,
                    goods_size : this.selection[0].goods_size,
                    num : this.info.edit_number,
                    remark : "",
                    weight : this.info.weight,
                    total_weight : this.info.weight,
                    goods_id : this.selection[0].goods_id,
                    overnumber : this.info.edit_number - 12,
                    overweight : (this.info.weight - Number(this.info.edit_number * this.selection[0].weight/1000)).toFixed(2)
                }
                this.form.size_data.push(tabData)
                setTimeout(()=>{
                    this.info.edit_number = 12
                },500)
            },
            selectAll() {
                this.$message.error("请选择一条数据！")
                this.$refs.tables.clearSelection()
            },
            // 单选
            selectionChange(selection) {
                if(this.show == true){
                    this.$message.error("请先点击开始收货！")
                    this.$refs.tables.clearSelection()
                }else{
                    if(selection.length > 1){
                        const del_row = selection.shift()
                        this.$refs.tables.toggleRowSelection(del_row,false) //设置这一行取消选中
                    }
                    this.selection = selection;
                    if(this.selection!=''){
                        if(this.selection.can_take_num<=0){
                            this.$message.error("可收数为0,无法继续收货")
                        }else{
                            this.info.expected_number = Math.ceil(Number(this.info.weight*1000) / Number(this.selection[0].weight))
                            let c = (this.info.weight - Number(this.selection[0].dozen_weight )).toFixed(2)
                            var MusicDuang = new Audio('https://zhiqiu.mzth.cn/static/img/duang.mp3');
                            if(this.info.weight > Number(this.selection[0].dozen_weight )){
                                this.checkTitle = "超重" + c + "KG," + "是否继续条码12件收货?"
                                this.dialog.weight = true
                                MusicDuang.play()
                            }
                            if(this.info.weight < Number(this.selection[0].dozen_weight)){
                                this.checkTitle = "超轻" + c + "KG," + "是否继续条码12件收货?"
                                this.dialog.weight = true
                                MusicDuang.play()
                            }
                        }
                    }
                }
            },
            // 点击确定
            confirm(){
                if(this.selection[0].can_take_num<=0){
                    this.$alert("超过最大可收数,无法继续收货", "提示", { type: 'error' })
                }else{
                    // var MusicYes = new Audio('https://zhiqiu.mzth.cn/static/img/yes.mp3');
                    // MusicYes.play()
                    if(this.selection[0].can_take_num<=this.info.expected_number){
                        // this.$alert("超过最大可收数,无法继续收货", "提示", { type: 'error' })
                        this.checkTitle = "超过最大可收数,请输入最大可收数"
                        this.dialog.weight = true
                    }else{
                        this.info.expected_number = Math.ceil(Number(this.info.weight*1000) / Number(this.selection[0].weight))
                        let c = (this.info.weight - Number(this.selection[0].dozen_weight)).toFixed(2)
                        if(this.info.weight > Number(this.selection[0].dozen_weight)){
                            this.checkTitle = "超重" + c + "KG," + "是否继续条码12件收货?"
                            this.dialog.weight = true
                        }
                        if(this.info.weight < Number(this.selection[0].dozen_weight)){
                            this.checkTitle = "超轻" + c + "KG," + "是否继续条码12件收货?"
                            this.dialog.weight = true
                        }
                        if(!this.dialog.weight){
                            var MusicYes = new Audio('https://zhiqiu.mzth.cn/static/img/yes.mp3');
                            MusicYes.play()
                            this.data.map(item=>{
                                if(item.goods_size == this.selection[0].goods_size){
                                    item.can_take_num = item.can_take_num - this.info.edit_number
                                }
                            })
                            let tabData = {
                            contract_no : this.form.contract_no,
                            batch_number : this.selection[0].batch_number,
                            colour : this.selection[0].color,
                            factory_number : this.info.factory_number,
                            process_title : this.info.produce_process_name,
                            goods_size : this.selection[0].goods_size,
                            num : this.info.weight_num,
                            remark : "",
                            weight : this.info.weight,
                            total_weight : this.info.weight,
                            goods_id : this.selection[0].goods_id,
                            overnumber : this.info.expected_number - 12,
                            overweight : (this.info.weight - Number(12 * this.selection[0].weight/1000)).toFixed(2)
                        }
                            this.form.size_data.push(tabData)
                        }else{
                            var MusicNo = new Audio('https://zhiqiu.mzth.cn/static/img/duang.mp3');
                            MusicNo.play()
                        }
                    }
                }
            },
            processChange(e){
                this.twoProcess.map(item=>{
                    if(e==item.id){
                        this.info.produce_process_name = item.title
                    }
                })
            },
        }
    }
</script>

<style></style>
